#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
from django.core.cache import cache
import requests
import re
from web.config.east_money_config import EastMoneyConfig
from web.domain.commodity_future_date_contract_data_api_result import CommodityFutureDateContractDataApiResult
from web.util.json_util import JsonUtil
from web.manager.log_manager import LogManager
from web.constants.k_line_period_type import KLinePeriodType
from web.task.base_task import BaseTask

Logger = LogManager.get_logger(__name__)

"""
定时任务：调用东方财富网的接口，下载商品期货交易的合约数据（通常在每天下午收盘之后，夜盘开始之前执行）
"""


class EastMoneyDownloadCollectCommodityFutureDateContractDataTask(BaseTask):

    def download_data(self, k_line_period_type):
        """
        调用东方财富网的接口，下载商品期货交易的合约数据（通常在每天下午收盘之后，夜盘开始之前执行）
        """

        Logger.info('调用东方财富网的接口，下载商品期货交易的合约数据（通常在每天下午收盘之后，夜盘开始之前执行）')

        exchange_list = EastMoneyConfig.Commodity_Future_Download_Url['Exchange']

        for exchange in exchange_list:
            for commodity_future in exchange['Commodity_Future_List']:
                page_index = 0
                while True:
                    url = commodity_future['Url_Pattern'].replace('#{pageIndex}', str(page_index))

                    # 发送HTTP请求
                    response = requests.get(url)

                    # 确认请求成功
                    if response.status_code == 200:
                        text = response.text
                        pattern = re.compile(r'^aaa_callback\((.+?)\)$')
                        matches = pattern.findall(text)
                        # Logger.info('接口返回的数据为' + matches[0])

                        commodity_future_date_contract_data_api_result = JsonUtil.json_to_class(matches[0], CommodityFutureDateContractDataApiResult)

                        if commodity_future_date_contract_data_api_result.list is not None and len(
                                commodity_future_date_contract_data_api_result.list) != 0:
                            # 1天级别
                            if k_line_period_type == KLinePeriodType.One_Day:
                                self.commodity_future_date_contract_data_service.save_commodity_future_date_contract_data_list_for_east_money(
                                    commodity_future_date_contract_data_api_result.list)
                            # 1小时级别
                            # if k_line_period_type == KLinePeriodType.One_Hour:
                            #     self.commodity_future_hour_data_service.save_commodity_future_hour_data_dto_list(
                            #         commodity_future_date_contract_data_api_result.list)
                            # # 30分钟级别
                            # if k_line_period_type == KLinePeriodType.Thirty_Minutes:
                            #     self.commodity_future_minute_data_service.save_commodity_future_minute_data_list(
                            #         commodity_future_date_contract_data_api_result.list)
                        else:
                            Logger.warn("list的长度为0，不再处理")
                            break
                    else:
                        Logger.error('调用接口失败')

                    page_index = page_index + 1

    def start_task(self):
        """
        启动定时任务任务
        """

        Logger.info('启动定时任务任务：EastMoneyDownloadCollectCommodityFutureDateContractDataTask')

        # 1天
        self.blocking_scheduler.add_job(
            self.download_data,
            'cron', day='*', hour='17', minute='37', id='download_data',
            args=[KLinePeriodType.One_Day])

        # 1小时
        # self.blocking_scheduler.add_job(
        #     self.collect_commodity_future_data,
        #     'cron', hour='*', minute='51', id='collect_commodity_future_hour_data',
        #     args=[KLinePeriodType.One_Hour])

        # 30分钟
        # self.blocking_scheduler.add_job(
        #     self.collect_commodity_future_data,
        #     'cron', hour='*', minute='0,27', id='collect_commodity_future_minute_data',
        #     args=[KLinePeriodType.Thirty_Minutes])

        self.blocking_scheduler.start()

        # 结束任务
        # self.blocking_scheduler.shutdown()
